<script lang="ts" setup>
import { ClickOutside as vClickOutside } from 'element-plus'
import L from 'leaflet'
import type { Marker } from 'leaflet'

const popVisible = ref(false)
const triggerRef = ref()
const mapRef = ref()
let marker: Marker | null = null

const show = (trigger: HTMLElement, lat: number, lng: number) => {
  triggerRef.value = trigger
  popVisible.value = true
  nextTick(() => {
    mapRef.value.loadMap()
    if (marker) marker.setLatLng([lat, lng])
    else {
      marker = L.marker([lat, lng])
      mapRef.value.map.addLayer(marker)
    }
    mapRef.value.map.setView([lat, lng], 16)
  })
}
const onClickOutside = () => {
  popVisible.value = false
}

defineExpose({
  show
})
</script>

<template>
  <el-popover
    :visible="popVisible"
    ref="popoverRef"
    :virtual-ref="triggerRef"
    trigger="click"
    virtual-triggering
    width="424"
    :teleported="false"
  >
    <div v-click-outside="onClickOutside" class="w-400 h-250 bg-#f7f7f7 rounded-4 overflow-hidden">
      <Map ref="mapRef" :isAutoLoad="false" />
    </div>
  </el-popover>
</template>
